<template>
    <div>
        <div style="color: #c0c4cc">
            新建时间：{{create_time}}&nbsp;&nbsp;&nbsp;&nbsp;最新跟新时间:{{update_time}}
        </div>
        <div style="padding: 20px 0px;">
            <button @click="()=>copyId()">复制id</button>
            <button v-if="!contenteditable" @click="()=>contenteditable=!contenteditable">编辑</button>
            <button @click="()=>{contenteditable=!contenteditable;save()}" v-if="contenteditable">保存</button>
<!--            <button style="margin-left: 10px;" @click="()=>{saveParent()}" v-if="puuid">绑定</button>-->
            <button  @click="()=>$router.push(`storyOne?uuid=${uuid}`)">预览</button>
            <button  @click="()=>$router.push(`storyList`)">我的列表</button>
<!--            <button  @click="()=>createA(`/story/html2png/${uuid}.png?uuid=${uuid}`)">导出</button>-->
        </div>

        <div style="display: flex">

            <el-input v-model="title" placeholder="标题" style="margin-bottom: 20px;"></el-input>
        </div>

        <div class="wrapperEdit" style="background: rgb(252, 250, 242);"
             :style="`${contenteditable?'border: 1px dash rgb(221, 221, 221);':'border: 1px solid rgb(221, 221, 221);'}`"
        >
            <!--   <div id="editor1" style="padding: 10px;">
               </div>
   -->
            <markdown-editor editorId="1" ref="editorRef" :initData="content"></markdown-editor>
        </div>


    </div>
</template>
<script>

    import {copy2bang, createA, getUrlParamNative, uuid} from "../../utils/utils";

    // import E from "wangeditor";

    function getSelection() {
        return rangy.getSelection().toString()
    }

    function getFirstRange() {
        var sel = rangy.getSelection();
        return sel.rangeCount ? sel.getRangeAt(0) : null;
    }

    function isInFrame() {
        if (self.frameElement && self.frameElement.tagName == "IFRAME") {
            return true;
        }
    }

    function openAlertList(text, puuid) {
        if (isInFrame()) {
            parent.openAlertList(text, uuid)
        } else {
            layer.open({
                type: 2,
                title: `【列表】 like ${text}`,
                shadeClose: false,
                shade: false,
                area: ['380px', '480px'],
                content: `/storyEditDailog?title=${text}&puuid=${puuid}` //iframe的url
            });
        }

    }

    window.openAlertList = openAlertList


    /*
    * @desc
    * 1.获取相同的 选中
    * 2 不喜欢 自己加
    * */
    async function clickLinkTextHandle(e) {
        var text = e.target.text.trim()
        if (text) {
            /*
            * @desc 1查询 text 如果有类似的文字 列表显示选中
            * 2选中
            * 2 不选择 自己新增一个文字
            * */
            var puuid = getUrlParamNative('uuid')
            openAlertList(text, puuid)
        }

    }

    /*打开 编辑器*/
    function openAlertStoryEdit(text, uuid, puuid) {
        if (isInFrame()) {
            parent.openAlertStoryEdit(text, uuid)
        } else {
            layer.open({
                type: 2,
                title: `【编辑】${text}`,
                shadeClose: false,
                shade: false,
                area: ['380px', '480px'],
                content: `/storyEdit?uuid=${uuid}&title=${text}&puuid=${puuid}` //iframe的url
            });
        }

    }

    window.openAlertStoryEdit = openAlertStoryEdit


    function reportSelectionText() {
        return rangy.getSelection().toString()
    }

    function reportSelectionHtml() {
        return rangy.getSelection().toHtml()
    }

    function getText(str1) {
        var re = /<[^>]+>/gi;
        return str1.replace(re, '');
    }

    function deleteSelection() {
        rangy.getSelection().deleteFromDocument();
    }

    function extractRange() {
        var range = getFirstRange();
        range.extractContents()
    }

    function insertNodeAtRange(insertEl) {
        var range = getFirstRange();
        if (range) {
            range.insertNode(insertEl);
            rangy.getSelection().setSingleRange(range);
        }
    }

    function surroundRange() {
        var range = getFirstRange();
        console.log("range", getSelection(), range)
        var html = reportSelectionHtml();
        var str = getText(html)
        if (range) {
            var el = document.createElement("a");
            el.href = `#${uuid()}_${getSelection()}`
            el.style.backgroundColor = "pink";
            el.onclick = clickLinkTextHandle
            el.text = str
            //delete + insert
            extractRange();
            insertNodeAtRange(el)
        }
    }

    function translateDialog(text) {
        if (isInFrame()) {
            parent.translateDialog(text)
        } else {
            layer.open({
                type: 2,
                title: `【翻译】${text}`,
                shadeClose: false,
                shade: false,
                area: ['380px', '480px'],
                content: `/storyTranslate?keyword=${text}` //iframe的url
            });
        }
    }
    window.translateDialog = translateDialog

    import moment from 'moment'

    export default {
        components: {
            "markdown-editor": () => import('./markdown-editor.vue')
        },
        data() {
            return {
                //父类的id
                puuid: "",
                contenteditable: true,
                title: "",
                content: "",
                contentHtml: "",
                isInFrameVar: isInFrame(),
                createA,
                create_time:"",
                update_time:"",
            }
        },
        mounted() {
            var _uuid = getUrlParamNative("uuid")
            if (!_uuid) {
                alert("检查到你没有uuid")
                location.href = `/#/storyEdit?uuid=${uuid()}`
                return false;
            }
            this.puuid = getUrlParamNative("puuid")
            this.uuid = _uuid
            //先去缓存获取内容
            this.title = sessionStorage.getItem("story_" + this.uuid + "_title") || getUrlParamNative("title") || ''
            this.content = sessionStorage.getItem("story_" + this.uuid + "_content") || ""
            this.update_time = sessionStorage.getItem("story_" + this.uuid + "_update_time") || ""
            this.create_time = sessionStorage.getItem("story_" + this.uuid + "_create_time") || ""
            if(this.title){
                document.title=   this.title
            }
            if (!this.content) {
                this.ajaxStoryDetail();

            }
            this.initEdit()
            /* this.requireEditor(() => {
                 this.initEdit()
                 if (!this.content) {
                     this.ajaxStoryDetail();
                 }
             })*/


        },
        methods: {
            copyId() {
                copy2bang(`[${this.title}](/storyOne?uuid=${this.uuid})`)
                this.$message('复制id成功')
            },
            requireEditor(callback) {
                let vm = this;
                //设置全局变量，因为editormd依赖jquery
                window.$ = window.jQuery = $;
                //异步加载并执行
                /*  $.getScript("/editor.md-master/editormd.js",function(script){
                      setTimeout(()=>{
                          callback();
                      },300)
                  })*/
                //加载css
                $('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', '/editor.md-master/css/editormd.min.css'));
                setTimeout(() => {
                    callback();
                }, 300)
            },
            initEdit() {
                var self = this;
                /*   const editor = new Editor({
                       el: document.querySelector('#editor1'),
                       previewStyle: 'vertical',
                       height: '500px',
                       initialEditType: 'markdown',
                       initialValue: this.content
                   });*/
                /*          // 删除默认监听事件
                          this.editor.eventManager.removeEventHandler('addImageBlobHook')
                          // 添加自定义监听事件
                          editor.eventManager.listen('addImageBlobHook', (blob, callback) => {
                              // 此处填写自己的上传逻辑，url为上传后的图片地址
                              this.uploadImage(blob, url => {
                                  console.log('callback"', url)
                                  callback(url)
                              })
                          })*/

                $('a').click(e => clickLinkTextHandle(e));
                document.onkeydown = onKeyDown;

                function onKeyDown(e) {
                    console.log("快捷键", e)
                    //快捷键alt+enter
                    if (e.altKey && e.keyCode == 13) {
                        console.log(getSelection())
                        // surroundRange()
                        var text = getSelection().trim() || $.selection()
                        if (text) {
                            /*
                            * @desc 1查询 text 如果有类似的文字 列表显示选中
                            * 2选中
                            * 2 不选择 自己新增一个文字
                            * */
                            var puuid = getUrlParamNative('uuid')
                            openAlertList(text, puuid)
                        }
                    }
                    //保存文字 停止其他出发
                    if (e.ctrlKey && e.keyCode == 83) {
                        self.save()
                        e.stopPropagation()
                        e.preventDefault();
                    }
                    //自动翻译 alt+t
                    if (e.altKey && e.keyCode == 84) {
                        var text = getSelection().trim() || $.selection()
                        if(text){
                            translateDialog(text)
                        }
                        e.stopPropagation()
                        e.preventDefault();
                    }
                }


            },

            uploadImage(blob, cb) {
                var form = new FormData()
                form.append('file', blob)
                return axios.post('/story/uploadImage', form, {
                    headers: {'Content-Type': 'multipart/form-data'}
                }).then(res => res.data).then(res => cb(res.url))
            },
            ajaxStoryDetail() {
                var self = this;
                axios.get(`/story/one?uuid=${this.uuid}`).then(res => res.data).then(detail => {
                    if (detail) {
                        this.title = detail.title
                        this.content = detail.content
                        this.create_time=moment(detail.create_time).format('YYYY-MM-DD hh:mm:ss')
                        this.update_time=moment(detail.update_time).format('YYYY-MM-DD hh:mm:ss')
                        if(   this.title){
                            document.title=   this.title
                        }
                        self.initEdit()
                    }

                })
            },
            save() {
                if (!this.title) {
                    alert("麻烦输入标题")
                    return false
                }

                const content = this.$refs['editorRef'].editor.getMarkdown();
                sessionStorage.setItem("story_" + this.uuid + "_title", this.title)
                sessionStorage.setItem("story_" + this.uuid + "_content", content)
                sessionStorage.setItem("story_" + this.uuid + "_update_time",   this.update_time)
                sessionStorage.setItem("story_" + this.uuid + "_create_time",   this.create_time)
                axios.post('/story/modify', {
                    uuid: this.uuid,
                    title: this.title,
                    content: content
                }).then(res => res.data).then(res => {
                    this.$message("保存成功")
                    this.ajaxmarke2Html(content)
                })
            },
            /*绑定这篇文档和父类的关系*/
            saveParent() {

            },
            ajaxmarke2Html(html) {
                axios.post(`/story/renderMarke2html`, {str: html}).then(res => res.data).then(resultHmtl => {
                    this.contentHtml = resultHmtl
                })
            }
        }
    }
</script>